/*
Copyright (C) 1996-1997 Id Software, Inc.

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.

*/

// draw.c -- this is the only file outside the refresh that touches the
// vid buffer

#include "quakedef.h"
#include <stdlib.h>

cvar_t		gl_nobind = {"gl_nobind", "0"};
cvar_t		gl_max_size = {"gl_max_size", "1024"};
cvar_t		gl_picmip = {"gl_picmip", "0"};
cvar_t      gl_gloss = {"gl_gloss", "0.3"};
cvar_t      gl_compress_textures = {"gl_compress_textures", "0"};
cvar_t      gl_gray_colormaps = {"gl_gray_colormaps", "0"};
cvar_t      con_clock = {"con_clock", "1", true};

byte		*draw_chars;				// 8*8 graphic characters
qpic_t		*draw_disc;
qpic_t		*draw_backtile;

int			char_texture;
int			translate_texture;
int			atten1d_texture_object;
int			atten2d_texture_object;
int			atten3d_texture_object;

typedef struct
{
    int		texnum;
    float	sl, tl, sh, th;
} glpic_t;

byte		conback_buffer[sizeof(qpic_t) + sizeof(glpic_t)];
qpic_t		*conback = (qpic_t *)&conback_buffer;

int		gl_lightmap_format = 4;
int		gl_solid_format = 3;
int		gl_alpha_format = 4;

int		gl_filter_min = GL_LINEAR_MIPMAP_LINEAR;
int		gl_filter_max = GL_LINEAR;
int		gl_max_size_default;

typedef struct
{
    int		texnum;
    char	identifier[64];
    int		width, height;
    int		scaled_width, scaled_height;
    int		mode;
} gltexture_t;

#define	MAX_GLTEXTURES	4096
gltexture_t	gltextures[MAX_GLTEXTURES];
int			numgltextures;

void GL_Bind (int texnum)
{
    if (gl_nobind.value)
    {
        texnum = char_texture;
    }

    if (currenttexture == texnum) return;
    currenttexture = texnum;
    glBindTexture(GL_TEXTURE_2D, texnum);
}

/*
=============================================================================

  scrap allocation

  Allocate all the little status bar obejcts into a single texture
  to crutch up stupid hardware / drivers

=============================================================================
*/

#define	MAX_SCRAPS		2
#define	BLOCK_WIDTH		256
#define	BLOCK_HEIGHT	256

int			scrap_allocated[MAX_SCRAPS][BLOCK_WIDTH];
byte		scrap_texels[MAX_SCRAPS][BLOCK_WIDTH*BLOCK_HEIGHT*4];
qboolean	scrap_dirty;
int			scrap_texnum;

// returns a texture number and the position inside it
int Scrap_AllocBlock (int w, int h, int *x, int *y)
{
    int		i, j;
    int		best, best2;
    int		texnum;

    for (texnum=0 ; texnum<MAX_SCRAPS ; texnum++)
    {
        best = BLOCK_HEIGHT;

        for (i=0 ; i<BLOCK_WIDTH-w ; i++)
        {
            best2 = 0;

            for (j=0 ; j<w ; j++)
            {
                if (scrap_allocated[texnum][i+j] >= best) break;
                if (scrap_allocated[texnum][i+j] > best2)
                {
                    best2 = scrap_allocated[texnum][i+j];
                }
            }

            if (j == w)
            {
                // this is a valid spot
                *x = i;
                *y = best = best2;
            }
        }

        if (best + h > BLOCK_HEIGHT) continue;

        for (i=0 ; i<w ; i++)
        {
            scrap_allocated[texnum][*x + i] = best + h;
        }
        return texnum;
    }
    Sys_Error ("Scrap_AllocBlock: full");

    return 0;
}

void Scrap_Upload (void)
{
    int		texnum;

    for (texnum = 0 ; texnum < MAX_SCRAPS ; texnum++)
    {
        GL_Bind(scrap_texnum + texnum);
        GL_LoadFromFile ("scrap", BLOCK_WIDTH, BLOCK_HEIGHT, scrap_texels[texnum], TEX_ALPHA);
    }
    scrap_dirty = false;
}

//=============================================================================

/* Support Routines */
typedef struct cachepic_s
{
    char		name[MAX_QPATH];
    qpic_t		pic;
    byte		padding[32];	// for appended glpic
} cachepic_t;

#define	MAX_CACHED_PICS		128
cachepic_t	menu_cachepics[MAX_CACHED_PICS];
int			menu_numcachepics;

byte		menuplyr_pixels[4096];

static int  pic_texels;
static int  pic_count;

qpic_t *Draw_PicFromWad (char *name)
{
    qpic_t	*p;
    glpic_t	*gl;

    p = W_GetLumpName (name);
    gl = (glpic_t *)p->data;

    // load little ones into the scrap
    if (p->width < 64 && p->height < 64)
    {
        int		x, y;
        int		i, j, k;
        int		texnum;

        texnum = Scrap_AllocBlock (p->width, p->height, &x, &y);

        scrap_dirty = true;

        k = 0;

        for (i=0 ; i<p->height ; i++)
        {
            for (j=0 ; j<p->width ; j++, k++)
            {
                scrap_texels[texnum][(y+i)*BLOCK_WIDTH + x + j] = p->data[k];
            }
        }
        texnum += scrap_texnum;
        gl->texnum = texnum;

        gl->sl = (x+0.01)/(float)BLOCK_WIDTH;
        gl->sh = (x+p->width-0.01)/(float)BLOCK_WIDTH;
        gl->tl = (y+0.01)/(float)BLOCK_WIDTH;
        gl->th = (y+p->height-0.01)/(float)BLOCK_WIDTH;

        pic_count++;
        pic_texels += p->width*p->height;
    }
    else
    {
        gl->texnum = GL_LoadPicTexture (p);
        gl->sl = 0;
        gl->sh = 1;
        gl->tl = 0;
        gl->th = 1;
    }
    return p;
}


/*
================
Draw_CachePic
================
*/
qpic_t	*Draw_CachePic (char *path)
{
    cachepic_t	*pic;
    int			i;
    qpic_t		*dat;
    glpic_t		*gl;

    for (pic=menu_cachepics, i=0 ; i<menu_numcachepics ; pic++, i++)
    {
        if (!strcmp (path, pic->name))
        {
            return &pic->pic;
        }
    }

    if (menu_numcachepics == MAX_CACHED_PICS)
    {
        Sys_Error ("menu_numcachepics == MAX_CACHED_PICS");
    }
    menu_numcachepics++;

    memcpy (pic->name, path, sizeof(pic->name));

//
// load the pic from disk
//
    dat = (qpic_t *)COM_LoadTempFile (path);

    if (!dat)
    {
        Sys_Error ("Draw_CachePic: failed to load %s", path);
    }
    SwapPic (dat);

    // HACK HACK HACK --- we need to keep the bytes for
    // the translatable player picture just for the menu
    // configuration dialog
    if (!strcmp (path, "gfx/menuplyr.lmp"))
    {
        memcpy (menuplyr_pixels, dat->data, dat->width*dat->height);
    }
    pic->pic.width = dat->width;
    pic->pic.height = dat->height;

    gl = (glpic_t *)pic->pic.data;
    gl->texnum = GL_LoadPicTexture (dat);

    gl->sl = 0;
    gl->sh = 1;
    gl->tl = 0;
    gl->th = 1;

    return &pic->pic;
}

void Draw_CharToConback (int num, byte *dest)
{
    int		row, col;
    byte	*source;
    int		drawline;
    int		x;

    row = num>>4;
    col = num&15;
    source = draw_chars + (row<<10) + (col<<3);

    drawline = 8;

    while (drawline--)
    {
        for (x=0 ; x<8 ; x++)
        {
            if (source[x] != 255)
            {
                dest[x] = 0x60 + source[x];
            }
        }
        source += 128;
        dest += 320;
    }
}

typedef struct
{
    char *name;
    int	minimize, maximize;
} glmode_t;

glmode_t modes[] =
{
    {"GL_NEAREST", GL_NEAREST, GL_NEAREST},
    {"GL_LINEAR", GL_LINEAR, GL_LINEAR},
    {"GL_NEAREST_MIPMAP_NEAREST", GL_NEAREST_MIPMAP_NEAREST, GL_NEAREST},
    {"GL_LINEAR_MIPMAP_NEAREST", GL_LINEAR_MIPMAP_NEAREST, GL_LINEAR},
    {"GL_NEAREST_MIPMAP_LINEAR", GL_NEAREST_MIPMAP_LINEAR, GL_NEAREST},
    {"GL_LINEAR_MIPMAP_LINEAR", GL_LINEAR_MIPMAP_LINEAR, GL_LINEAR}
};

/*
===============
Draw_TextureMode_f
===============
*/
void Draw_TextureMode_f (void)
{
    int		    i;
    gltexture_t	*glt;

    if (Cmd_Argc() == 1)
    {
        for (i=0 ; i< 6 ; i++)
		{
            if (gl_filter_min == modes[i].minimize)
            {
                Con_Printf ("%s\n", modes[i].name);
                return;
            }
		}
        Con_Printf ("current filter is unknown???\n");
        return;
    }

    for (i=0 ; i< 6 ; i++)
    {
        if (!Q_strcasecmp (modes[i].name, Cmd_Argv(1) ) )  break;
    }

    if (i == 6)
    {
        Con_Printf ("bad filter name\n");
        return;
    }
    gl_filter_min = modes[i].minimize;
    gl_filter_max = modes[i].maximize;

    // change all the existing mipmap texture objects
    for (i=0, glt=gltextures ; i<numgltextures ; i++, glt++)
    {
        if (glt->mode & TEX_MIPMAP)
        {
            GL_Bind (glt->texnum);
            glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, gl_filter_min);
            glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, gl_filter_max);

            //PENTA: also update bump maps
            GL_Bind (glt->texnum+1);
            glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, gl_filter_min);
            glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, gl_filter_max);
        }
    }
}

/*
===============
Draw_Init
===============
*/
void Draw_Init (void)
{
    int			i;
    qpic_t		*cb;
    byte		*dest;
    int			x, y;
    char		ver[40];
    glpic_t		*gl;
    int			start;
    byte		*ncdata;

    Cvar_RegisterVariable (&gl_nobind, NULL);
    Cvar_RegisterVariable (&gl_max_size, NULL);
    Cvar_RegisterVariable (&gl_picmip, NULL);
    Cvar_RegisterVariable (&gl_gloss, NULL);
    Cvar_RegisterVariable (&gl_compress_textures, NULL);
    Cvar_RegisterVariable (&gl_gray_colormaps, NULL);
    Cvar_RegisterVariable (&con_clock, NULL);

    // 3dfx can only handle 256 wide textures
    if (!Q_strncasecmp ((char *)gl_renderer, "3dfx",4) || strstr((char *)gl_renderer, "Glide"))
    {
        Cvar_Set ("gl_max_size", "256");
    }
    else
    {
        glGetIntegerv (GL_MAX_TEXTURE_SIZE, &gl_max_size_default);
        Cvar_SetValue ("gl_max_size", gl_max_size_default);
    }
    Cmd_AddCommand ("gl_texturemode", &Draw_TextureMode_f);

    // load the console background and the charset
    // by hand, because we need to write the version
    // string into the background before turning
    // it into a texture
    draw_chars = W_GetLumpName ("conchars");

    for (i=0 ; i<256*64 ; i++)
    {
        if (draw_chars[i] == 0)
        {
            draw_chars[i] = 255;	// proper transparent color
        }
    }

    // now turn them into textures
    char_texture = GL_LoadTexture ("charset", 128, 128, draw_chars, TEX_ALPHA);

    start = Hunk_LowMark();

    cb = (qpic_t *) COM_LoadTempFile ("gfx/conback.lmp");

    if (!cb)
    {
        Sys_Error ("Couldn't load gfx/conback.lmp");
    }
    SwapPic (cb);

    // hack the version number directly into the pic
#if defined(__linux__)
    sprintf (ver, "(Linux %2.2f, gl %4.2f) %4.2f", (float)LINUX_VERSION, (float)GLQUAKE_VERSION, (float)VERSION);
#elif defined (__APPLE__) || defined (MACOSX)
    sprintf (ver, "(MACOS X %2.2f, gl %4.2f) %4.2f", (float)MACOSX_VERSION, (float)GLQUAKE_VERSION, (float)VERSION);
#else
    sprintf (ver, "(st %4.2f) %4.2f", (float)STQUAKE_VERSION, (float)VERSION);
#endif
    dest = cb->data + 320 * 186 + 320 - 11 - 8 * strlen(ver);
    y = strlen(ver);

    for (x=0 ; x<y ; x++)
    {
        Draw_CharToConback (ver[x], dest + (x << 3));
    }
    conback->width = cb->width;
    conback->height = cb->height;
    ncdata = cb->data;

    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);

    gl = (glpic_t *)conback->data;
    gl->texnum = GL_LoadTexture ("conback", conback->width, conback->height, ncdata, TEX_NONE);

    gl->sl = 0;
    gl->sh = 1;
    gl->tl = 0;
    gl->th = 1;

    conback->width = vid.width;
    conback->height = vid.height;

    // free loaded console
    Hunk_FreeToLowMark(start);

    // save a texture slot for translated picture
    translate_texture = texture_extension_number++;

    // save slots for scraps
    scrap_texnum = texture_extension_number;
    texture_extension_number += MAX_SCRAPS;

    //
    // get the other pics we need
    //
    draw_disc = Draw_PicFromWad ("disc");
    draw_backtile = Draw_PicFromWad ("backtile");

    //Load nomalization cube map
    atten1d_texture_object = GL_LoadNormalizationCubemap();

    //PENTA: load fallof glow
    atten2d_texture_object = GL_Load2DAttenTexture();
    atten3d_texture_object = GL_Load3DAttenTexture();

    //load diffuse vertex program
    R_LoadVertexProgram();

    //load mirror dummys
    R_InitMirrorChains();

    // load glares
    R_InitGlare();
}



/*
================
Draw_Character

Draws one 8*8 graphics character with 0 being transparent.
It can be clipped to the top of the screen to allow the console to be
smoothly scrolled off.
================
*/
void Draw_Character (int x, int y, int num)
{
    int		row, col;
    float	frow, fcol, size;

    if (num == 32) return;	// space
    num &= 255;
    if (y <= -8) return;	// totally off screen

    row = num>>4;
    col = num&15;

    frow = row*0.0625;
    fcol = col*0.0625;
    size = 0.0625;

    glEnable(GL_BLEND);
    GL_Bind (char_texture);

    glBegin (GL_QUADS);
    glTexCoord2f (fcol, frow);
    glVertex2f (x, y);
    glTexCoord2f (fcol + size, frow);
    glVertex2f (x+8, y);
    glTexCoord2f (fcol + size, frow + size);
    glVertex2f (x+8, y+8);
    glTexCoord2f (fcol, frow + size);
    glVertex2f (x, y+8);
    glEnd ();
    glDisable(GL_BLEND);
}

/*
================
Draw_String
================
*/
void Draw_String (int x, int y, char *str)
{
    while (*str)
    {
        Draw_Character (x, y, *str);
        str++;
        x += 8;
    }
}

/*
================
Draw_DebugChar

Draws a single character directly to the upper right corner of the screen.
This is for debugging lockups by drawing different chars in different parts
of the code.
================
*/
void Draw_DebugChar (char num)
{
}

/*
=============
Draw_AlphaPic
=============
*/
void Draw_AlphaPic (int x, int y, qpic_t *pic, float alpha)
{
    glpic_t			*gl;

    if (scrap_dirty)
	{
        Scrap_Upload ();
	}
    gl = (glpic_t *)pic->data;
    glDisable(GL_ALPHA_TEST);
    glEnable (GL_BLEND);
    glColor4f (1,1,1,alpha);
    GL_Bind (gl->texnum);
    glBegin (GL_QUADS);
    glTexCoord2f (gl->sl, gl->tl);
    glVertex2f (x, y);
    glTexCoord2f (gl->sh, gl->tl);
    glVertex2f (x+pic->width, y);
    glTexCoord2f (gl->sh, gl->th);
    glVertex2f (x+pic->width, y+pic->height);
    glTexCoord2f (gl->sl, gl->th);
    glVertex2f (x, y+pic->height);
    glEnd ();
    glColor4f (1,1,1,1);
    glEnable(GL_ALPHA_TEST);
    glDisable (GL_BLEND);
}


/*
=============
Draw_Pic
=============
*/
void Draw_Pic (int x, int y, qpic_t *pic)
{
    glpic_t			*gl;

    if (scrap_dirty)
	{
        Scrap_Upload ();
	}
    gl = (glpic_t *)pic->data;
    glColor4f (1,1,1,1);
    GL_Bind (gl->texnum);
    glBegin (GL_QUADS);
    glTexCoord2f (gl->sl, gl->tl);
    glVertex2f (x, y);
    glTexCoord2f (gl->sh, gl->tl);
    glVertex2f (x+pic->width, y);
    glTexCoord2f (gl->sh, gl->th);
    glVertex2f (x+pic->width, y+pic->height);
    glTexCoord2f (gl->sl, gl->th);
    glVertex2f (x, y+pic->height);
    glEnd ();
}

/*
=============
Draw_TransPic
=============
*/
void Draw_TransPic (int x, int y, qpic_t *pic)
{
    if (x < 0 || (unsigned)(x + pic->width) > vid.width || y < 0 || (unsigned)(y + pic->height) > vid.height) return;
    Draw_Pic (x, y, pic);
}

/*
=============
Draw_TransPicTranslate

Only used for the player color selection menu
=============
*/
void Draw_TransPicTranslate (int x, int y, qpic_t *pic, byte *translation)
{
    int				v, u;
    unsigned		trans[64*64], *dest;
    byte			*src;
    int				p;

    GL_Bind (translate_texture);

    dest = trans;

    for (v=0 ; v<64 ; v++, dest += 64)
    {
        src = &menuplyr_pixels[ ((v*pic->height)>>6) *pic->width];

        for (u=0 ; u<64 ; u++)
        {
            p = src[(u * pic->width) >> 6];

            if (p == 255)
			{
                dest[u] = p;
			}
            else
			{
                dest[u] =  d_8to24table[translation[p]];
			}
        }
    }
    glTexImage2D (GL_TEXTURE_2D, 0, gl_alpha_format, 64, 64, 0, GL_RGBA, GL_UNSIGNED_BYTE, trans);

    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

    glColor3f (1,1,1);
    glBegin (GL_QUADS);
    glTexCoord2f (0, 0);
    glVertex2f (x, y);
    glTexCoord2f (1, 0);
    glVertex2f (x+pic->width, y);
    glTexCoord2f (1, 1);
    glVertex2f (x+pic->width, y+pic->height);
    glTexCoord2f (0, 1);
    glVertex2f (x, y+pic->height);
    glEnd ();
}


/*
================
Draw_ConsoleBackground

================
*/
void Draw_ConsoleBackground (int lines)
{
    int		y = (vid.height * 3) >> 2;
    int		x, i;
    char	tl[80]; //Console Clock - Eradicator
    char	timebuf[20];

    if (lines > y)
	{
        Draw_Pic(0, lines - vid.height, conback);
	}
    else
	{
        Draw_AlphaPic (0, lines - vid.height, conback, (float)(1.2 * lines)/y);
	}

    if ( con_clock.value )
    {
        Sys_Strtime( timebuf );
        y = lines-14;
        sprintf (tl, "Time: %s",timebuf); //Console Clock - Eradicator
        x = vid.conwidth - (vid.conwidth*12/vid.width*12) + 30;

        for (i=0 ; i < (int) strlen(tl) ; i++)
		{
            Draw_Character (x + i * 8, y, tl[i] | 0x80);
		}
    }
}

void Draw_SpiralConsoleBackground (int lines) //Spiral Console - Eradicator
{
    int				x, y, i;
    static float	xangle = 0, xfactor = 0.3f, xstep = 0.01f;
    char			tl[80]; //Console Clock - Eradicator
    char			timebuf[20];

    Sys_Strtime( timebuf );

    glPushMatrix();
    glMatrixMode(GL_TEXTURE);
    glPushMatrix();

    glLoadIdentity();
    xangle += 1.0f;
    xfactor += xstep;

    if (xfactor > 8 || xfactor < 0.3f)
	{
        xstep = -xstep;
	}
    glRotatef(xangle, 0, 0, 1);
    glScalef(xfactor, xfactor, xfactor);
    y = (vid.height * 3) >> 2;

    if (lines > y)
	{
        Draw_Pic(0, lines-vid.height, conback);
	}
    else
	{
        Draw_AlphaPic (0, lines - vid.height, conback, (float)(1.2 * lines) / y);
	}
    glPopMatrix();
    glMatrixMode(GL_MODELVIEW);
    glPopMatrix();

    if ( con_clock.value )
    {
        y = lines-14;
        sprintf (tl, "Time: %s", timebuf); //Console Clock - Eradicator
        x = vid.conwidth - (vid.conwidth * 12 / vid.width * 12) + 30;

        for (i=0 ; i < (int) strlen(tl) ; i++)
		{
            Draw_Character (x + i * 8, y, tl[i] | 0x80);
		}
    }
}


/*
=============
Draw_TileClear

This repeats a 64*64 tile graphic to fill the screen around a sized down
refresh window.
=============
*/
void Draw_TileClear (int x, int y, int w, int h)
{
    glColor3f (1,1,1);
    GL_Bind (*(int *)draw_backtile->data);
    glBegin (GL_QUADS);
    glTexCoord2f (x/64.0, y/64.0);
    glVertex2f (x, y);
    glTexCoord2f ( (x+w)/64.0, y/64.0);
    glVertex2f (x+w, y);
    glTexCoord2f ( (x+w)/64.0, (y+h)/64.0);
    glVertex2f (x+w, y+h);
    glTexCoord2f ( x/64.0, (y+h)/64.0 );
    glVertex2f (x, y+h);
    glEnd ();
}


/*
=============
Draw_Fill

Fills a box of pixels with a single color
=============
*/
void Draw_Fill (int x, int y, int w, int h, int c)
{
    glDisable (GL_TEXTURE_2D);
    glColor3f (host_basepal[c*3]/255.0, host_basepal[c*3+1]/255.0, host_basepal[c*3+2]/255.0);

    glBegin (GL_QUADS);

    glVertex2f (x,y);
    glVertex2f (x+w, y);
    glVertex2f (x+w, y+h);
    glVertex2f (x, y+h);

    glEnd ();
    glColor3f (1,1,1);
    glEnable (GL_TEXTURE_2D);
}
//=============================================================================

/*
================
Draw_FadeScreen

================
*/
void Draw_FadeScreen (void)
{
    glEnable (GL_BLEND);
    glDisable (GL_TEXTURE_2D);
    glColor4f (0, 0, 0, 0.8f);
    glBegin (GL_QUADS);

    glVertex2f (0, 0);
    glVertex2f (vid.width, 0);
    glVertex2f (vid.width, vid.height);
    glVertex2f (0, vid.height);

    glEnd ();
    glColor4f (1,1,1,1);
    glEnable (GL_TEXTURE_2D);
    glDisable (GL_BLEND);

    Sbar_Changed();
}

//=============================================================================

/*
================
Draw_BeginDisc

Draws the little blue disc in the corner of the screen.
Call before beginning any disc IO.
================
*/
void Draw_BeginDisc (void)
{
    if (!draw_disc) return;
    glDrawBuffer  (GL_FRONT);
    Draw_Pic (vid.width - 24, 0, draw_disc);
    glDrawBuffer  (GL_BACK);
}


/*
================
Draw_EndDisc

Erases the disc icon.
Call after completing any disc IO
================
*/
void Draw_EndDisc (void)
{
}

/*
================
GL_Set2D

Setup as if the screen was 320*200
================
*/
void GL_Set2D (void)
{
    glViewport (glx, gly, glwidth, glheight);

    glMatrixMode(GL_PROJECTION);
    glLoadIdentity ();
    glOrtho(0, vid.width, vid.height, 0, -99999, 99999);
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity ();

    glDisable (GL_DEPTH_TEST);
    glDisable (GL_CULL_FACE);
    glEnable (GL_ALPHA_TEST);

    glEnable(GL_BLEND);
    glAlphaFunc(GL_GREATER, 0.666f);

    glColor4f (1, 1, 1, 1);
}

//====================================================================

/* messy stuff below warning */
static	unsigned int	trans[4096*4096];
static	unsigned char	glosspix[4096*4096];
static	unsigned char	bumppix[4096*4096];

/*
================
GL_FindTexture
================
*/
int GL_FindTexture (char *identifier)
{
    int			i;
    gltexture_t	*glt;

    for (i=0, glt=gltextures ; i<numgltextures ; i++, glt++)
    {
        if (!strcmp (identifier, glt->identifier))
        {
            return gltextures[i].texnum;
        }
    }
    return -1;
}

/*
================
GL_ResampleTextureLerpLine

Interpolates between pixels on line - Eradicator
================
*/
void GL_ResampleTextureLerpLine (byte *in, byte *out, int inwidth, int outwidth)
{
    int		j, xi, oldx = 0, f, fstep, endx;

    fstep = (int) (inwidth * 65536.0f / outwidth);
    endx = (inwidth-1);

    for (j = 0,f = 0; j < outwidth; j++, f += fstep)
    {
        xi = (int) f >> 16;

        if (xi != oldx)
        {
            in += (xi - oldx) * 4;
            oldx = xi;
        }

        if (xi < endx)
        {
            int lerp = f & 0xFFFF;
            *out++ = (byte) ((((in[4] - in[0]) * lerp) >> 16) + in[0]);
            *out++ = (byte) ((((in[5] - in[1]) * lerp) >> 16) + in[1]);
            *out++ = (byte) ((((in[6] - in[2]) * lerp) >> 16) + in[2]);
            *out++ = (byte) ((((in[7] - in[3]) * lerp) >> 16) + in[3]);
        }
        else
        {
            *out++ = in[0];
            *out++ = in[1];
            *out++ = in[2];
            *out++ = in[3];
        }
    }
}

/*
================
GL_ResampleTexture
================
*/
void GL_ResampleTexture (void *indata, int inwidth, int inheight, void *outdata,  int outwidth, int outheight)
{
    //New Interpolated Texture Code - Eradicator
    int		i, j, yi, oldy, f, fstep, endy = (inheight-1);
    byte	*inrow, *out, *row1, *row2;

    out = outdata;
    fstep = (int) (inheight*65536.0f/outheight);

    row1 = malloc(outwidth*4);
    row2 = malloc(outwidth*4);

    inrow = indata;
    oldy = 0;

    GL_ResampleTextureLerpLine (inrow, row1, inwidth, outwidth);
    GL_ResampleTextureLerpLine (inrow + inwidth*4, row2, inwidth, outwidth);

    for (i = 0, f = 0; i < outheight; i++,f += fstep)
    {
        yi = f >> 16;

        if (yi < endy)
        {
            int lerp = f & 0xFFFF;

            if (yi != oldy)
            {
                inrow = (byte *)indata + inwidth * 4 * yi;

                if (yi == oldy + 1)
                {
                    memcpy(row1, row2, outwidth * 4);
                }
                else
                {
                    GL_ResampleTextureLerpLine (inrow, row1, inwidth, outwidth);
                }
                GL_ResampleTextureLerpLine (inrow + inwidth*4, row2, inwidth, outwidth);

                oldy = yi;
            }
            j = outwidth - 4;

            while(j >= 0)
            {
                out[ 0] = (byte) ((((row2[ 0] - row1[ 0]) * lerp) >> 16) + row1[ 0]);
                out[ 1] = (byte) ((((row2[ 1] - row1[ 1]) * lerp) >> 16) + row1[ 1]);
                out[ 2] = (byte) ((((row2[ 2] - row1[ 2]) * lerp) >> 16) + row1[ 2]);
                out[ 3] = (byte) ((((row2[ 3] - row1[ 3]) * lerp) >> 16) + row1[ 3]);
                out[ 4] = (byte) ((((row2[ 4] - row1[ 4]) * lerp) >> 16) + row1[ 4]);
                out[ 5] = (byte) ((((row2[ 5] - row1[ 5]) * lerp) >> 16) + row1[ 5]);
                out[ 6] = (byte) ((((row2[ 6] - row1[ 6]) * lerp) >> 16) + row1[ 6]);
                out[ 7] = (byte) ((((row2[ 7] - row1[ 7]) * lerp) >> 16) + row1[ 7]);
                out[ 8] = (byte) ((((row2[ 8] - row1[ 8]) * lerp) >> 16) + row1[ 8]);
                out[ 9] = (byte) ((((row2[ 9] - row1[ 9]) * lerp) >> 16) + row1[ 9]);
                out[10] = (byte) ((((row2[10] - row1[10]) * lerp) >> 16) + row1[10]);
                out[11] = (byte) ((((row2[11] - row1[11]) * lerp) >> 16) + row1[11]);
                out[12] = (byte) ((((row2[12] - row1[12]) * lerp) >> 16) + row1[12]);
                out[13] = (byte) ((((row2[13] - row1[13]) * lerp) >> 16) + row1[13]);
                out[14] = (byte) ((((row2[14] - row1[14]) * lerp) >> 16) + row1[14]);
                out[15] = (byte) ((((row2[15] - row1[15]) * lerp) >> 16) + row1[15]);

                out += 16;
                row1 += 16;
                row2 += 16;
                j -= 4;
            }

            if (j & 2)
            {
                out[ 0] = (byte) ((((row2[ 0] - row1[ 0]) * lerp) >> 16) + row1[ 0]);
                out[ 1] = (byte) ((((row2[ 1] - row1[ 1]) * lerp) >> 16) + row1[ 1]);
                out[ 2] = (byte) ((((row2[ 2] - row1[ 2]) * lerp) >> 16) + row1[ 2]);
                out[ 3] = (byte) ((((row2[ 3] - row1[ 3]) * lerp) >> 16) + row1[ 3]);
                out[ 4] = (byte) ((((row2[ 4] - row1[ 4]) * lerp) >> 16) + row1[ 4]);
                out[ 5] = (byte) ((((row2[ 5] - row1[ 5]) * lerp) >> 16) + row1[ 5]);
                out[ 6] = (byte) ((((row2[ 6] - row1[ 6]) * lerp) >> 16) + row1[ 6]);
                out[ 7] = (byte) ((((row2[ 7] - row1[ 7]) * lerp) >> 16) + row1[ 7]);

                out += 8;
                row1 += 8;
                row2 += 8;
            }

            if (j & 1)
            {
                out[ 0] = (byte) ((((row2[ 0] - row1[ 0]) * lerp) >> 16) + row1[ 0]);
                out[ 1] = (byte) ((((row2[ 1] - row1[ 1]) * lerp) >> 16) + row1[ 1]);
                out[ 2] = (byte) ((((row2[ 2] - row1[ 2]) * lerp) >> 16) + row1[ 2]);
                out[ 3] = (byte) ((((row2[ 3] - row1[ 3]) * lerp) >> 16) + row1[ 3]);

                out += 4;
                row1 += 4;
                row2 += 4;
            }
            row1 -= outwidth*4;
            row2 -= outwidth*4;
        }
        else
        {
            if (yi != oldy)
            {
                inrow = (byte *)indata + inwidth*4*yi;

                if (yi == oldy + 1)
                {
                    memcpy(row1, row2, outwidth * 4);
                }
                else
                {
                    GL_ResampleTextureLerpLine (inrow, row1, inwidth, outwidth);
                }
                oldy = yi;
            }
            memcpy(out, row1, outwidth * 4);
        }
    }
    free(row1);
    free(row2);
}


/*
================
GL_Resample8BitTexture -- JACK
================
*/
void GL_Resample8BitTexture (unsigned char *in, int inwidth, int inheight, unsigned char *out,  int outwidth, int outheight)
{
    int			i, j;
    unsigned	char *inrow;
    unsigned	frac, fracstep;

    fracstep = inwidth*0x10000/outwidth;

    for (i=0 ; i<outheight ; i++, out += outwidth)
    {
        inrow = in + inwidth*(i*inheight/outheight);
        frac = fracstep >> 1;

        for (j=0 ; j<outwidth ; j+=4)
        {
            out[j] = inrow[frac>>16];
            frac += fracstep;
            out[j+1] = inrow[frac>>16];
            frac += fracstep;
            out[j+2] = inrow[frac>>16];
            frac += fracstep;
            out[j+3] = inrow[frac>>16];
            frac += fracstep;
        }
    }
}

/*
================
GL_MipMap

Operates in place, quartering the size of the texture
================
*/
void GL_MipMap (byte *in, int width, int height)
{
    int		i, j;
    byte	*out;

    width <<=2;
    height >>= 1;
    out = in;

    for (i=0 ; i<height ; i++, in+=width)
    {
        for (j=0 ; j<width ; j+=8, out+=4, in+=8)
        {
            out[0] = (in[0] + in[4] + in[width+0] + in[width+4])>>2;
            out[1] = (in[1] + in[5] + in[width+1] + in[width+5])>>2;
            out[2] = (in[2] + in[6] + in[width+2] + in[width+6])>>2;
            out[3] = (in[3] + in[7] + in[width+3] + in[width+7])>>2;
        }
    }
}

/*
================
GL_MipMapNormal

Operates in place, quartering the size of the texture
Works on normal maps instead of rgb
================
*/
void GL_MipMapNormal (byte *in, int width, int height)
{
    int		i, j;
    byte	*out;
    float	x, y, z, l, mag00, mag01, mag10, mag11;

    width <<= 2;
    height >>= 1;
    out = in;

    for (i=0 ; i<height ; i++, in+=width)
    {
        for (j=0 ; j<width ; j+=8, out+=4, in+=8)
        {
            mag00 = ONEOVER255 * in[3];
            mag01 = ONEOVER255 * in[7];
            mag10 = ONEOVER255 * in[width+3];
            mag11 = ONEOVER255 * in[width+7];

            x = mag00*(ONEOVER127*in[0]-1.0)+
                mag01*(ONEOVER127*in[4]-1.0)+
                mag10*(ONEOVER127*in[width+0]-1.0)+
                mag11*(ONEOVER127*in[width+4]-1.0);
            y = mag00*(ONEOVER127*in[1]-1.0)+
                mag01*(ONEOVER127*in[5]-1.0)+
                mag10*(ONEOVER127*in[width+1]-1.0)+
                mag11*(ONEOVER127*in[width+5]-1.0);
            z = mag00*(ONEOVER127*in[2]-1.0)+
                mag01*(ONEOVER127*in[6]-1.0)+
                mag10*(ONEOVER127*in[width+2]-1.0)+
                mag11*(ONEOVER127*in[width+6]-1.0);

            l = sqrt(x * x + y * y + z * z);

            if (l == 0.0)
            {
                x = 0.0;
                y = 0.0;
                z = 1.0;
            }
            else
            {
                //normalize it.
                l = 1.0f / l;
                x *= l;
                y *= l;
                z *= l;
            }
            out[0] = (unsigned char)128 + 127 * x;
            out[1] = (unsigned char)128 + 127 * y;
            out[2] = (unsigned char)128 + 127 * z;

            l = l / 4.0;

            if (l > 1.0)
            {
                out[3] = 255;
            }
            else
            {
                out[3] = (byte)(255.0 * l);
            }
        }
    }
}

/*
================
GL_MipMap8Bit

Mipping for 8 bit textures
================
*/
void GL_MipMap8Bit (byte *in, int width, int height)
{
    int					i, j;
    unsigned short		r, g, b;
    byte				*out, *at1, *at2, *at3, *at4;

    height >>= 1;
    out = in;

    for (i=0 ; i<height ; i++, in+=width)
    {
        for (j=0 ; j<width ; j+=2, out+=1, in+=2)
        {
            at1 = (byte *) (d_8to24table + in[0]);
            at2 = (byte *) (d_8to24table + in[1]);
            at3 = (byte *) (d_8to24table + in[width+0]);
            at4 = (byte *) (d_8to24table + in[width+1]);

            r = (at1[0]+at2[0]+at3[0]+at4[0]);
            r >>= 5;

            g = (at1[1]+at2[1]+at3[1]+at4[1]);
            g >>= 5;

            b = (at1[2]+at2[2]+at3[2]+at4[2]);
            b >>= 5;

            out[0] = d_15to8table[(r << 0) + (g << 5) + (b << 10)];
        }
    }
}

/*
===============
GL_MakeNormal
===============
*/
void GL_MakeNormal(byte *in, int width, int height)
{
    int		i, j;
    byte	*out;
    float	x, y, z, l;

    width <<= 2;
    out = in;

    for (i=0 ; i<height ; i++)
    {
        for (j=0 ; j<width ; j+=4, out+=4, in+=4)
        {
            x = (ONEOVER127 * in[0] - 1.0);
            y = (ONEOVER127 * in[1] - 1.0);
            z = (ONEOVER127 * in[2] - 1.0);

            l = sqrt(x * x + y * y + z * z);

            if (l == 0.0f)
            {
                x = 0.0;
                y = 0.0;
                z = 1.0;
            }
            else
            {
                //normalize it.
                l = 1.0f / l;
                x *= l;
                y *= l;
                z *= l;
            }
            out[0] = (unsigned char)128 + 127 * x;
            out[1] = (unsigned char)128 + 127 * y;
            out[2] = (unsigned char)128 + 127 * z;
        }
    }
}

/*
===============
GL_HeightmapToNormalmap
===============
*/
static unsigned int *GL_HeightmapToNormalmap(byte *in, int width, int height, int mode)
{
    int		                i, j, wr, hr;
    unsigned char	        r, g, b;
    static unsigned int     nmap[4096*4096];
    float	                sqlen, reciplen, nx, ny, nz;
    float	                c, cx, cy, dcx, dcy;

    wr = width;
    hr = height;

    for (i=0; i<height; i++)
    {
        for (j=0; j<width; j++)
        {
            /* Expand [0,255] texel values to the [0,1] range. */
            c = in[i * wr + j] * ONEOVER255;

            /* Expand the texel to its right. */
            cx = in[i * wr + (j + 1) % wr] * ONEOVER255;

            /* Expand the texel one up. */
            cy = in[((i + 1) % hr) * wr + j] * ONEOVER255;

            /* scale it according to source */
            dcx = (mode & TEX_SCALE) ? 10.0f : 4.0f * (c - cx);
            dcy = (mode & TEX_SCALE) ? 10.0f : 4.0f * (c - cy);

            /* Normalize the vector. */
            sqlen = dcx * dcx + dcy * dcy + 1;
            reciplen = 1.0f / (float) sqrt(sqlen);
            nx = dcx * reciplen;
            ny = -dcy * reciplen;
            nz = reciplen;

            /* Repack the normalized vector into an RGB unsigned byte
               vector in the normal map image. */
            r = (byte) (128 + 127 * nx);
            g = (byte) (128 + 127 * ny);
            b = (byte) (128 + 127 * nz);

            /* The highest resolution mipmap level always has a
               unit length magnitude. */
            nmap[i * width + j] = LittleLong ((in[i * wr + j] << 24) | (b << 16) | (g << 8) | (r));	// <AWE> Added support for big endian.
        }
    }
    return &nmap[0];
}

/*
===============
GL_PackGloss

Packs a gloss byte in destination
===============
*/
void GL_PackGloss(byte *gloss, unsigned *dest, int length)
{
    int i;

    for (i=0; i<length; i++, gloss++, dest++)
    {
        *dest = *dest & LittleLong (0x00FFFFFF);	// <AWE> Added support for big endian.
        *dest = *dest | LittleLong (*gloss << 24);	// <AWE> Added support for big endian.
    }
}

/*
================
ScaleDimensions
================
*/
void GL_ScaleDimensions (int width, int height, int *scaled_width, int *scaled_height, int mode)
{
    int	maxsize;

    for (*scaled_width = 1 ; *scaled_width < width ; *scaled_width *= 2);
    for (*scaled_height = 1 ; *scaled_height < height ; *scaled_height *= 2);

    if (mode & TEX_MIPMAP)
    {
        *scaled_width >>= (int)gl_picmip.value;
        *scaled_height >>= (int)gl_picmip.value;
    }
    maxsize = (mode & TEX_MIPMAP) ? gl_max_size.value : gl_max_size_default;

    *scaled_width = bound(1, *scaled_width, maxsize);
    *scaled_height = bound(1, *scaled_height, maxsize);
}

/*
===============
GL_UploadColor
===============
*/
void GL_UploadColor (unsigned *data, int width, int height, int mode)
{
    static	unsigned	scaled[4096*4096];
    int					scaled_width, scaled_height;
    int                 internal_format, format;

    if ( gl_gray_colormaps.value )
    {
        Q_memset(data, 0x7f, width * height * 4);
    }
    GL_ScaleDimensions (width, height, &scaled_width, &scaled_height, mode);

    format = ( gl_texcomp && ((int)gl_compress_textures.value) & 1 ) ? GL_COMPRESSED_RGBA_ARB : GL_RGBA;
    internal_format = (mode & TEX_ALPHA) ? gl_alpha_format : gl_solid_format;

    if (scaled_width == width && scaled_height == height)
    {
        if (!(mode & TEX_MIPMAP))
        {
            glTexImage2D (GL_TEXTURE_2D, 0, internal_format, scaled_width, scaled_height, 0, format, GL_UNSIGNED_BYTE, data);
            goto done;
        }
        memcpy (scaled, data, width * height * 4);
    }
    else
    {
        GL_ResampleTexture (data, width, height, scaled, scaled_width, scaled_height);
    }
    glTexImage2D (GL_TEXTURE_2D, 0, internal_format, scaled_width, scaled_height, 0, format, GL_UNSIGNED_BYTE, scaled);

    if (mode & TEX_MIPMAP)
    {
        int		miplevel = 0;

        while (scaled_width > 1 || scaled_height > 1)
        {
            GL_MipMap ((byte *)scaled, scaled_width, scaled_height);

            scaled_width >>= 1;
            scaled_height >>= 1;

            if (scaled_width < 1)
            {
                scaled_width = 1;
            }

            if (scaled_height < 1)
            {
                scaled_height = 1;
            }
            miplevel++;

            glTexImage2D (GL_TEXTURE_2D, miplevel, internal_format, scaled_width, scaled_height, 0, format, GL_UNSIGNED_BYTE, scaled);
        }
    }
done:
    ;

    if (mode & TEX_MIPMAP)
    {
        glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, gl_filter_min);
        glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, gl_filter_max);
    }
    else
    {
        glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, gl_filter_max);
        glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, gl_filter_max);
    }

    if (gl_texturefilteranisotropic)
    {
        glTexParameterfv (GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, &gl_textureanisotropylevel);
    }
}

void GL_UploadColor8 (byte *data, int width, int height, int mode)
{
    static unsigned char 	scaled[4096*4096];
    int						scaled_width, scaled_height;

    GL_ScaleDimensions (width, height, &scaled_width, &scaled_height, mode);

    if (scaled_width == width && scaled_height == height)
    {
        if (!(mode & TEX_MIPMAP))
        {
            glTexImage2D (GL_TEXTURE_2D, 0, GL_COLOR_INDEX8_EXT, scaled_width, scaled_height, 0, GL_COLOR_INDEX , GL_UNSIGNED_BYTE, data);
            goto done;
        }
        memcpy (scaled, data, width*height);
    }
    else
    {
        GL_Resample8BitTexture (data, width, height, scaled, scaled_width, scaled_height);
    }
    glTexImage2D (GL_TEXTURE_2D, 0, GL_COLOR_INDEX8_EXT, scaled_width, scaled_height, 0, GL_COLOR_INDEX, GL_UNSIGNED_BYTE, scaled);

    if (mode & TEX_MIPMAP)
    {
        int		miplevel = 0;

        while (scaled_width > 1 || scaled_height > 1)
        {
            GL_MipMap8Bit ((byte *)scaled, scaled_width, scaled_height);

            scaled_width >>= 1;
            scaled_height >>= 1;

            if (scaled_width < 1)
            {
                scaled_width = 1;
            }

            if (scaled_height < 1)
            {
                scaled_height = 1;
            }
            miplevel++;

            glTexImage2D (GL_TEXTURE_2D, miplevel, GL_COLOR_INDEX8_EXT, scaled_width, scaled_height, 0, GL_COLOR_INDEX, GL_UNSIGNED_BYTE, scaled);
        }
    }
done:
    ;

    if (mode & TEX_MIPMAP)
    {
        glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, gl_filter_min);
        glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, gl_filter_max);
    }
    else
    {
        glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, gl_filter_max);
        glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, gl_filter_max);
    }

    if (gl_texturefilteranisotropic)
    {
        glTexParameterfv (GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, &gl_textureanisotropylevel);
    }
}

void GL_UploadNormal(unsigned int *data, int width, int height, int mode)
{
    static unsigned int	scaled[4096*4096];
    int					scaled_width, scaled_height;
    int					internal_format, format;

    //Resize to power of 2 and maximum texture size
    GL_ScaleDimensions (width, height, &scaled_width, &scaled_height, mode);

    //To resize or not to resize
    if (scaled_width == width && scaled_height == height)
    {
        memcpy (scaled, data, width*height*4);
        scaled_width = width;
        scaled_height = height;
    }
    else
    {
        GL_ResampleTexture (data, width, height, scaled, scaled_width, scaled_height);
    }
    GL_MakeNormal((byte *)scaled, scaled_width, scaled_height);

    format = ( gl_texcomp && ((int)gl_compress_textures.value) & 1 ) ? GL_COMPRESSED_RGBA_ARB : GL_RGBA;
    internal_format = (mode & TEX_ALPHA) ? gl_alpha_format : gl_solid_format;

    glTexImage2D (GL_TEXTURE_2D, 0, internal_format, scaled_width, scaled_height, 0, format, GL_UNSIGNED_BYTE, scaled);

    if (mode & TEX_MIPMAP)
    {
        int		miplevel = 0;

        while (scaled_width > 1 || scaled_height > 1)
        {
            GL_MipMapNormal((byte *)scaled, scaled_width, scaled_height);

            scaled_width >>= 1;
            scaled_height >>= 1;

            if (scaled_width < 1)
            {
                scaled_width = 1;
            }

            if (scaled_height < 1)
            {
                scaled_height = 1;
            }
            miplevel++;

            glTexImage2D (GL_TEXTURE_2D, miplevel, internal_format, scaled_width, scaled_height, 0, format, GL_UNSIGNED_BYTE, scaled);
        }
    }

    if (mode & TEX_MIPMAP)
    {
        glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, gl_filter_min);
        glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, gl_filter_max);
    }
    else
    {
        glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, gl_filter_max);
        glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, gl_filter_max);
    }

    if (gl_texturefilteranisotropic)
    {
        glTexParameterfv (GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, &gl_textureanisotropylevel);
    }
}

void GL_UploadBump(byte *data, int width, int height, int mode)
{
    static unsigned char	scaled[4096*4096];
    byte					*scalednormal;
    int						scaled_width, scaled_height;
    int						internal_format, format;

    //Resize to power of 2 and maximum texture size
    GL_ScaleDimensions (width, height, &scaled_width, &scaled_height, mode);

    //To resize or not to resize
    if (scaled_width == width && scaled_height == height)
    {
        memcpy (scaled, data, width*height);
        scaled_width = width;
        scaled_height = height;
    }
    else
    {
        //Just picks pixels so grayscale is equivalent with 8 bit.
        GL_Resample8BitTexture (data, width, height, scaled, scaled_width, scaled_height);
    }
    format = ( gl_texcomp && ((int)gl_compress_textures.value) & 1 ) ? GL_COMPRESSED_RGBA_ARB : GL_RGBA;
    internal_format = (mode & TEX_ALPHA) ? gl_alpha_format : gl_solid_format;

    scalednormal = (unsigned char *) GL_HeightmapToNormalmap(scaled, scaled_width, scaled_height, mode);

    glTexImage2D (GL_TEXTURE_2D, 0, internal_format, scaled_width, scaled_height, 0, format, GL_UNSIGNED_BYTE, scalednormal);

    if (mode & TEX_MIPMAP)
    {
        int		miplevel = 0;

        while (scaled_width > 1 || scaled_height > 1)
        {
            GL_MipMapNormal(scalednormal, scaled_width, scaled_height);

            scaled_width >>= 1;
            scaled_height >>= 1;

            if (scaled_width < 1)
            {
                scaled_width = 1;
            }

            if (scaled_height < 1)
            {
                scaled_height = 1;
            }
            miplevel++;

            glTexImage2D (GL_TEXTURE_2D, miplevel, internal_format, scaled_width, scaled_height, 0, format, GL_UNSIGNED_BYTE, scalednormal);
        }
    }

    if (mode & TEX_MIPMAP)
    {
        glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, gl_filter_min);
        glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, gl_filter_max);
    }
    else
    {
        glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, gl_filter_max);
        glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, gl_filter_max);
    }

    if (gl_texturefilteranisotropic)
    {
        glTexParameterfv (GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, &gl_textureanisotropylevel);
    }
}

/*
===============
GL_GetOverrideName
===============
*/
void GL_GetOverrideName(char *identifier, char *tail, char *dest)
{
    unsigned	i;

    va_snprintf(dest, MAX_OSPATH, "override/%s%s.ext", identifier, tail);

    for (i=0; i<strlen(dest); i++)
    {
        if (dest[i] == '*')
        {
            dest[i] = '%';
        }
    }
}

/*
===============
GL_ConvertPalette

Handles palette conversion and searches
the image for alpha pixels.
===============
*/
void GL_ConvertPalette (unsigned char *data, unsigned int *trans2, unsigned char *bumppix2, int size, int mode)
{
    int	i, p;

    /* check pixels */
    if (mode & TEX_ALPHA)
    {
        /* set to invalid at start */
        mode &= ~TEX_ALPHA;

        for (i=0 ; i<size ; i++)
        {
            p = data[i];

            /* if byte equals 255 then we have an alpha channel */
            if (p == 255)
            {
                mode |= TEX_ALPHA;
            }
            trans2[i] = d_8to24table[p];
            bumppix2[i] = d_8to8graytable[p];
        }
    }
    else
    {
        /* no alpha convert the palette and upload like a 3 component texture */
        mode &= ~TEX_ALPHA;

        for (i=0 ; i<size ; i+=4)
        {
            trans2[i] = d_8to24table[data[i]];
            trans2[i+1] = d_8to24table[data[i+1]];
            trans2[i+2] = d_8to24table[data[i+2]];
            trans2[i+3] = d_8to24table[data[i+3]];

            bumppix2[i] = d_8to8graytable[data[i]];
            bumppix2[i+1] = d_8to8graytable[data[i+1]];
            bumppix2[i+2] = d_8to8graytable[data[i+2]];
            bumppix2[i+3] = d_8to8graytable[data[i+3]];
        }
    }
}

/*
===============
GL_ConvertPixels

Handles Color conversion
===============
*/
void GL_ConvertPixels (unsigned int *in, unsigned char *out, int size)
{
    int		i;
    byte	r, g, b;

    for (i=0; i<size; i++)
    {
        r = (in[i] & 0x00FF0000) >> 16;
        g = (in[i] & 0x0000FF00) >> 8;
        b = (in[i] & 0x000000FF);
        out[i] = (r + g + b) / 3;
    }
}

/*
===============
GL_LoadFromFile

Attempt at making a better texture managment system.
===============
*/
void GL_LoadFromFile (char *identifier, int width, int height, byte *data, int mode)
{
    int			size;
    char		colormap[MAX_OSPATH];
    char		normalmap[MAX_OSPATH];
    char		bumpmap[MAX_OSPATH];
    char		glossmap[MAX_OSPATH];

    // get size
    size = width * height;

    // upload a colormap
    GL_GetOverrideName(identifier, "", colormap);

    if (Image_LoadTextureInPlace(colormap, 4, (unsigned char *)&trans[0], &width, &height))
    {
        Con_DPrintf("Overriding colormap for %s\n", identifier);

        mode |= TEX_SCALE;

        GL_ConvertPixels (trans, bumppix, size);
    }
    else
    {
        Con_DPrintf("Applying 8 to 32 bit conversion for %s\n", identifier);

        GL_ConvertPalette (data, trans, bumppix, size, mode);
    }

    //upload scrap texels
    if (!strcmp("scrap", identifier))
    {
        GL_UploadColor (trans, width, height, mode);
        return;
    }

    //force it to upload a 32 bit texture
    GL_Bind(texture_extension_number);

    GL_UploadColor (trans, width, height, mode);

    texture_extension_number++;

    if (!COM_CheckParm("-nobumpmaps") && (sh_bumpmaps.value) && (mode & TEX_BUMP))
    {
        GL_Bind(texture_extension_number);

        GL_GetOverrideName(identifier, "_norm", normalmap);

        // now try a normalmap
        if (Image_LoadTextureInPlace(normalmap, 4, (unsigned char *)&trans[0], &width, &height))
        {
            int	gwidth = 0, gheight = 0;

            Con_DPrintf("Overriding normal map for %s\n",identifier);

            GL_GetOverrideName(identifier, "_gloss", glossmap);

            if (Image_LoadTextureInPlace(glossmap, 1, &glosspix[0], &gwidth, &gheight))
            {
                Con_DPrintf("Overriding gloss map for %s\n", identifier);
            }
            else
            {
                //set some gloss by default
                gwidth = width;
                gheight = height;
                Q_memset(&glosspix[0], 255*gl_gloss.value, size);
            }

            // if the textures match pack gloss in the alpha channel of dest
            if ((gwidth != width) && (gheight != height))
            {
                Con_SafePrintf("\002Warning: %s Gloss map must have same size as color map\n", identifier);
            }
            else
            {
                GL_PackGloss(glosspix, trans, size);
            }
            GL_UploadNormal (trans, width, height, mode);
        }
        else
        {
            // if no normalmap try a greyscale bumpmap
            GL_GetOverrideName(identifier, "_bump", bumpmap);

            if (Image_LoadTextureInPlace(bumpmap, 1, (unsigned char *)&bumppix[0], &width, &height))
            {
                int	gwidth = 0, gheight = 0;

                Con_DPrintf("Overriding bump map for %s\n", identifier);

                GL_GetOverrideName(identifier, "_gloss", glossmap);

                if (Image_LoadTextureInPlace(glossmap, 1, &glosspix[0], &gwidth, &gheight))
                {
                    Con_DPrintf("Overriding gloss map for %s\n", identifier);
                }
                else
                {
                    //set some gloss by default
                    gwidth = width;
                    gheight = height;
                    Q_memset(&glosspix[0], 255 * gl_gloss.value, size);
                }

                // if the textures match pack gloss in the alpha channel of dest
                if ((gwidth != width) && (gheight != height))
                {
                    Con_SafePrintf("\002Warning: %s Gloss map must have same size as color map\n", identifier);
                }
                else
                {
                    GL_PackGloss(glosspix, (unsigned int *)bumppix, size);
                }
            }
            GL_UploadBump (bumppix, width, height, mode);
        }
    }
    texture_extension_number++;
}

/*
===============
GL_LoadLumaTexture
===============
*/
int GL_LoadLumaTexture(char *identifier, int width, int height, int mode)
{
    int  i;
    char lumamap[MAX_OSPATH];

    if (gl_gray_colormaps.value) return 0;

    GL_GetOverrideName(identifier, "_luma", lumamap);

    if (Image_LoadTextureInPlace(lumamap, 4, (unsigned char *)&trans[0], &width, &height))
    {
        /* scale the heightmap on lumas wtf ??? */
        mode |= TEX_SCALE;

        /* check if the alpha channel really works */
        if (mode & TEX_ALPHA)
        {
            mode &= ~TEX_ALPHA;

            for (i=0 ; i<width*height ; i++)
            {
                if ((((trans)[i] >> 24) & 0xFF) < 255)
                {
                    mode |= TEX_ALPHA;
                    break;
                }
            }
        }
        GL_Bind(texture_extension_number);

        GL_UploadColor (trans, width, height, mode);

        texture_extension_number++;

        return texture_extension_number-1;
    }
    return 0;
}

/*
================
GL_LoadTexture
================
*/
int GL_LoadTexture (char *identifier, int width, int height, byte *data, int mode)
{
    int			i, scaled_width, scaled_height;
    gltexture_t	*glt;

    GL_ScaleDimensions (width, height, &scaled_width, &scaled_height, mode);

    // see if the texture is allready present
    if (identifier[0])
    {
        for (i=0, glt=gltextures ; i<numgltextures ; i++, glt++)
        {
            if (!strncmp(identifier, glt->identifier, sizeof(glt->identifier)))
            {
                if (width != glt->width || height != glt->height || scaled_width != glt->scaled_width || scaled_height != glt->scaled_height)
                {
                    Con_Printf ("%s: warning: textures dont match\n", identifier);
                }
                return gltextures[i].texnum;
            }
        }
    }
    glt = &gltextures[numgltextures];
    numgltextures++;

    memcpy (glt->identifier, identifier, sizeof(glt->identifier));

    glt->texnum = texture_extension_number;
    glt->width = width;
    glt->height = height;
    glt->scaled_width = scaled_width;
    glt->scaled_height = scaled_height;
    glt->mode = mode;

    GL_LoadFromFile(identifier, width, height, data, mode);

    return texture_extension_number-2;
}

char *face_names[] =
{
    "posx",
    "negx",
    "posy",
    "negy",
    "posz",
    "negz",
};

/*
================
GL_LoadCubeMapTexture
================
*/
int GL_LoadCubeMapTexture (char *identifier)
{
    gltexture_t	*glt;
    int			i, width = 0, height = 0;

    // see if the texture is allready present
    if (identifier[0])
    {
        for (i=0, glt=gltextures ; i<numgltextures ; i++, glt++)
        {
            if (!strncmp(identifier, glt->identifier, sizeof(glt->identifier)))
            {
                return gltextures[i].texnum;
            }
        }
    }
    glt = &gltextures[numgltextures];
    numgltextures++;

    memcpy (glt->identifier, identifier, sizeof(glt->identifier));

    glEnable(GL_TEXTURE_CUBE_MAP_ARB);
    glBindTexture(GL_TEXTURE_CUBE_MAP_ARB, texture_extension_number);
    glTexParameteri(GL_TEXTURE_CUBE_MAP_ARB, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE );
    glTexParameteri(GL_TEXTURE_CUBE_MAP_ARB, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE );
    glTexParameteri(GL_TEXTURE_CUBE_MAP_ARB, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_CUBE_MAP_ARB, GL_TEXTURE_MIN_FILTER, GL_LINEAR);

    for (i = 0; i < 6; i++)
    {
        char cubetex[MAX_OSPATH];

        va_snprintf(cubetex, MAX_OSPATH, "%s%s.tga", identifier, face_names[i]);

        if (!(Image_LoadTextureInPlace(cubetex, 4, (unsigned char *)&trans[0], &width, &height)))
        {
            Con_Printf("Couldnt load cubemap texture %s\n", cubetex);
            return 0;
        }
        glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X_ARB+i, 0, ( gl_texcomp && ((int)gl_compress_textures.value) & 4 ) ? GL_COMPRESSED_RGBA_ARB : GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, &trans[0]);
    }
    glDisable(GL_TEXTURE_CUBE_MAP_ARB);

    glt->texnum = texture_extension_number;
    glt->width = width;
    glt->height = height;

    texture_extension_number++;

    return texture_extension_number-1;
}

/*
================
GL_LoadPicTexture
================
*/
int GL_LoadPicTexture (qpic_t *pic)
{
    return GL_LoadTexture ("", pic->width, pic->height, pic->data, TEX_ALPHA);
}

/****************************************/

static GLint	    cnttextures[16] = {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1};     // cached
static GLenum       oldtarget = GL_TEXTURE0_ARB;
static GLboolean    mtexenabled = false;

void GL_SelectTexture (GLenum target)
{
    if (!gl_mtexable) return;
    qglActiveTextureARB(target);
    if (target == oldtarget) return;
    cnttextures[oldtarget - GL_TEXTURE0_ARB] = currenttexture;
    currenttexture = cnttextures[target - GL_TEXTURE0_ARB];
    oldtarget = target;
}

void GL_DisableMultitexture(void)
{
    if (mtexenabled)
    {
        glDisable(GL_TEXTURE_2D);
        GL_SelectTexture(GL_TEXTURE0_ARB);
        mtexenabled = false;
    }
}

void GL_EnableMultitexture(void)
{
    if (gl_mtexable)
    {
        GL_SelectTexture(GL_TEXTURE1_ARB);
        glEnable(GL_TEXTURE_2D);
        mtexenabled = true;
    }
}

void GL_EnableTMU (GLenum target)
{
    GL_SelectTexture (target);
    glEnable (GL_TEXTURE_2D);
}

void GL_DisableTMU (GLenum target)
{
    GL_SelectTexture (target);
    glDisable (GL_TEXTURE_2D);
}

/****************************************/

#define NC_SIZE 128             // Size of the cube faces
#define ATTEN_VOLUME_SIZE 64    // Size of the atten glow texture
#define SQUARE(x) ((x)*(x))

/*
===============
PENTA:

Load texture for 2d atten
===============
*/
int GL_Load2DAttenTexture(void)
{
    float   centerx, centery, radiussq;
    int     s, t, err;
    byte    *data;

    data = malloc(ATTEN_VOLUME_SIZE*ATTEN_VOLUME_SIZE);

    if (!data) return 0;							// <AWE> check memory here!

    centerx = ATTEN_VOLUME_SIZE/2.0;
    centery = ATTEN_VOLUME_SIZE/2.0;
    radiussq = ATTEN_VOLUME_SIZE/2.0;
    radiussq = radiussq*radiussq;

    for (s = 0; s < ATTEN_VOLUME_SIZE; s++)
    {
        for (t = 0; t < ATTEN_VOLUME_SIZE; t++)
        {
            float DistSq = SQUARE(s-centerx) + SQUARE(t-centery);

            if (DistSq < radiussq)
            {
                byte    value;
                float   FallOff = (radiussq - DistSq) / radiussq;

                FallOff *= FallOff;
                value = FallOff*255.0;

                data[t * ATTEN_VOLUME_SIZE + s] = value;
            }
            else
            {
                data[t * ATTEN_VOLUME_SIZE + s] = 0;
            }
        }
    }
    GL_Bind(texture_extension_number);

    glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, ATTEN_VOLUME_SIZE, ATTEN_VOLUME_SIZE, 0, GL_ALPHA, GL_UNSIGNED_BYTE, data);

    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE );
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE );
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);

    free(data);

    texture_extension_number++;

    err  = glGetError();

    if (err != GL_NO_ERROR)
    {
        Con_Printf("%s",gluErrorString(err));
    }
    return texture_extension_number-1;
}

/*
===============
PENTA:

Load texture for 3d atten (on gf3)
===============
*/
int GL_Load3DAttenTexture(void)
{
    float   centerx, centery, centerz, radiussq;
    int     s, t, r, err;
    byte    *data;

    if (gl_cardtype == GENERIC || gl_cardtype == GEFORCE) return 0;//PA:

    data = malloc(ATTEN_VOLUME_SIZE*ATTEN_VOLUME_SIZE*ATTEN_VOLUME_SIZE*4);

    if (!data) return 0;							// <AWE> check memory here!

    centerx = ATTEN_VOLUME_SIZE/2.0;
    centery = ATTEN_VOLUME_SIZE/2.0;
    centerz = ATTEN_VOLUME_SIZE/2.0;
    radiussq = ATTEN_VOLUME_SIZE/2.0;
    radiussq = radiussq*radiussq;

    for (s = 0; s < ATTEN_VOLUME_SIZE; s++)
    {
        for (t = 0; t < ATTEN_VOLUME_SIZE; t++)
        {
            for (r = 0; r < ATTEN_VOLUME_SIZE; r++)
            {
                float DistSq = SQUARE(s-centerx)+SQUARE(t-centery)+SQUARE(r-centerz);

                if (DistSq < radiussq)
                {
                    byte    value;
                    float   FallOff = (radiussq - DistSq) / radiussq;

                    FallOff *= FallOff;
                    value = FallOff*255.0;

                    data[r * ATTEN_VOLUME_SIZE * ATTEN_VOLUME_SIZE *4+ t * ATTEN_VOLUME_SIZE *4+ s *4+ 0] = value;
                    data[r * ATTEN_VOLUME_SIZE * ATTEN_VOLUME_SIZE *4+ t * ATTEN_VOLUME_SIZE *4+ s *4+ 1] = value;
                    data[r * ATTEN_VOLUME_SIZE * ATTEN_VOLUME_SIZE *4+ t * ATTEN_VOLUME_SIZE *4+ s *4+ 2] = value;
                    data[r * ATTEN_VOLUME_SIZE * ATTEN_VOLUME_SIZE *4+ t * ATTEN_VOLUME_SIZE *4+ s *4+ 3] = value;
                }
                else
                {
                    data[r * ATTEN_VOLUME_SIZE * ATTEN_VOLUME_SIZE *4+ t * ATTEN_VOLUME_SIZE *4+ s *4+ 0] = 0;
                    data[r * ATTEN_VOLUME_SIZE * ATTEN_VOLUME_SIZE *4+ t * ATTEN_VOLUME_SIZE *4+ s *4+ 1] = 0;
                    data[r * ATTEN_VOLUME_SIZE * ATTEN_VOLUME_SIZE *4+ t * ATTEN_VOLUME_SIZE *4+ s *4+ 2] = 0;
                    data[r * ATTEN_VOLUME_SIZE * ATTEN_VOLUME_SIZE *4+ t * ATTEN_VOLUME_SIZE *4+ s *4+ 3] = 0;
                }

            }
        }
    }
    glBindTexture(GL_TEXTURE_3D, texture_extension_number);

    qglTexImage3DEXT(GL_TEXTURE_3D, 0, 4, ATTEN_VOLUME_SIZE, ATTEN_VOLUME_SIZE, ATTEN_VOLUME_SIZE, 0, GL_RGBA, GL_UNSIGNED_BYTE, data);

    glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE );
    glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE );
    glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE );
    glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);

    free(data);
    texture_extension_number++;

    err  = glGetError();

    if (err != GL_NO_ERROR)
    {
        Con_Printf("%s",gluErrorString(err));
    }
    return texture_extension_number-1;
}

/*
Code from:

bumpdemo.c - glamour demo of "normal perturbation" mapping
by Nvidia

*/

void GL_CubeVector(int i, int cubesize, int x, int y, float *vector)
{
    float s, t, sc, tc, mag;

    s = ((float)x + 0.5f) / (float)cubesize;
    t = ((float)y + 0.5f) / (float)cubesize;

    sc = s*2.0f - 1.0f;
    tc = t*2.0f - 1.0f;

    switch (i)
    {
    case 0:
        vector[0] = 1.0f;
        vector[1] = -tc;
        vector[2] = -sc;
        break;
    case 1:
        vector[0] = -1.0;
        vector[1] = -tc;
        vector[2] = sc;
        break;
    case 2:
        vector[0] = sc;
        vector[1] = 1.0;
        vector[2] = tc;
        break;
    case 3:
        vector[0] = sc;
        vector[1] = -1.0;
        vector[2] = -tc;
        break;
    case 4:
        vector[0] = sc;
        vector[1] = -tc;
        vector[2] = 1.0;
        break;
    case 5:
        vector[0] = -sc;
        vector[1] = -tc;
        vector[2] = -1.0;
        break;
    default:
        break;
    }
    mag = 1.0f / sqrt(vector[0]*vector[0] + vector[1]*vector[1] + vector[2]*vector[2]);

    vector[0] *= mag;
    vector[1] *= mag;
    vector[2] *= mag;
}

int GL_LoadNormalizationCubemap(void)
{
    vec3_t  vec;
    int     i, x, y;
    char    pixels [NC_SIZE*NC_SIZE*3];

    glEnable(GL_TEXTURE_CUBE_MAP_ARB);
    glBindTexture(GL_TEXTURE_CUBE_MAP_ARB, texture_extension_number);
    glTexParameteri(GL_TEXTURE_CUBE_MAP_ARB, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE );
    glTexParameteri(GL_TEXTURE_CUBE_MAP_ARB, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE );
    glTexParameteri(GL_TEXTURE_CUBE_MAP_ARB, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_CUBE_MAP_ARB, GL_TEXTURE_MIN_FILTER, GL_LINEAR);

    for (i = 0; i < 6; i++)
    {
        for (y = 0; y < NC_SIZE; y++)
        {
            for (x = 0; x < NC_SIZE; x++)
            {
                GL_CubeVector(i, NC_SIZE, x, y, vec);
                pixels[3*(y*NC_SIZE+x) + 0] = (unsigned char)(128 + 127*vec[0]);
                pixels[3*(y*NC_SIZE+x) + 1] = (unsigned char)(128 + 127*vec[1]);
                pixels[3*(y*NC_SIZE+x) + 2] = (unsigned char)(128 + 127*vec[2]);
            }
        }
        glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X_ARB+i, 0, GL_RGB8, NC_SIZE, NC_SIZE, 0, GL_RGB, GL_UNSIGNED_BYTE, &pixels);
    }
    glDisable(GL_TEXTURE_CUBE_MAP_ARB);

    texture_extension_number++;

    return texture_extension_number-1;
}
